<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, reactive, watch, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/index.js'
import { userRegisterService, userLoginService, getUserInfoService, getMenusService } from '@/api/user.js'
import { ElMessage, ElNotification } from 'element-plus'
const router = useRouter()
const userStore = useUserStore()
const to = inject('to')
const isRegister = ref(false)
// 表单数据
const registerForm = reactive({
  username: '',
  password: '',
  repassword: ''
})
const loginForm = reactive({
  username: '',
  password: ''
})
// 校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
// 记住我
const rememberMe = ref(false)
const firstLoading = ref(true)
// 切换注册登录
watch(isRegister, () => {
  resetForm()
})
onMounted(() => {
  firstLoading.value = false
  const loginInfo = JSON.parse(localStorage.getItem('loginInfo'))
  if (loginInfo) {
    loginForm.username = loginInfo.username
    loginForm.password = loginInfo.password
    rememberMe.value = true
  } else {
    rememberMe.value = false
  }
})
// 注册
const loading = ref(false)
const register = async (registerForm) => {
  try {
    loading.value = true
    await form.value.validate()
    const userRegister = await userRegisterService(registerForm)
    console.log(userRegister)
    if (userRegister.data.code === 0) {
      loading.value = false
      isRegister.value = true
      resetForm()

      ElNotification({
        title: '注册成功',
        message: '账号注册成功，请登录',
        type: 'success'
      })
    }
  } catch (e) {
    loading.value = false
  }
}
let num = 0
const recursion = (menuList) => {
  menuList.forEach((item) => {
    if (item?.children?.length >= 1) {
      if (item.title === '文章管理') {
        item.icon = 'Grid'
      } else if (item.title === '个人中心') {
        item.icon = 'User'
      }
      recursion(item.children)
    } else {
      if (item.title === '首页') {
        item.icon = 'HomeFilled'
      } else if (item.title === '文章分类') {
        item.icon = 'FolderOpened'
      } else if (item.title === '文章列表') {
        item.icon = 'Document'
      } else if (item.title === '基本资料') {
        item.icon = 'Setting'
      } else if (item.title === '更换头像') {
        item.icon = 'Avatar'
      } else if (item.title === '重置密码') {
        item.icon = 'Lock'
      }
    }
    menuList.push(
      {
        title: '测试页' + num++,
        icon: 'HomeFilled',
        indexPath: '/' + num++,
        hidden: false,
        children: []
      },
      {
        title: '测试页pro' + num++,
        icon: 'HomeFilled',
        indexPath: '/' + num++,
        hidden: false,
        children: [
          {
            title: '测试页1' + num++,
            icon: 'HomeFilled',
            indexPath: '/1' + num++,
            hidden: false,
            children: []
          },
          {
            title: '测试页2' + num++,
            icon: 'HomeFilled',
            indexPath: '/2' + num++,
            hidden: false,
            children: []
          }
        ]
      }
    )
  })
}
const login = async (loginForm) => {
  await form.value?.validate()
  loading.value = true
  const [login, loginError] = await to(userLoginService(loginForm))
  console.log(login, loginError)
  if (login && login.data?.code === 0) {
    await userStore.setToken(login.data?.token)
    ElNotification({
      title: '登录成功',
      message: '账号登录成功',
      type: 'success'
    })
    if (rememberMe.value) {
      localStorage.setItem('loginInfo', JSON.stringify(loginForm))
    } else {
      localStorage.removeItem('loginInfo')
    }
    const [userInfo, userInfoError] = await to(getUserInfoService()) //获取用户信息
    if (userInfo) {
      userStore.setUserInfo(userInfo.data.data)
    } else if (userInfoError) {
      ElMessage({
        type: 'error',
        message: userInfo.data?.msg ?? '获取用户信息失败'
      })
    }
    const [menus, menusError] = await to(getMenusService())
    if (menus.data?.code === 0) {
      recursion(menus.data.data)
      userStore.setMenus(menus.data.data)
    } else if (menusError) {
      ElMessage({
        type: 'error',
        message: menus.data?.msg ?? '获取菜单失败'
      })
    }
    await to(router.push('/'))
  }
  if (loginError) {
    loading.value = false
  }
}
// 重置表单
const form = ref(null)
const resetForm = () => {
  if (!form.value) return
  form.value.resetFields()
}
</script>

<template>
  <el-space style="width: 100%; display: block">
    <el-skeleton style="width: 100%; height: 100%" :loading="firstLoading" animated :count="1">
      <template #template>
        <div style="display: flex; justify-content: space-between; align-items: center; height: 100vh">
          <el-skeleton-item variant="image" style="width: 100%; height: 100%; border-radius: 0 20px 20px" />
          <div style="width: 100%">
            <div style="display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative">
              <div style="height: auto; width: 50%; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%)">
                <el-skeleton-item variant="text" style="width: 40%; height: 30px; margin: 10px 0" />
                <el-skeleton-item variant="text" style="width: 100%; height: 30px; margin: 10px 0" />
                <el-skeleton-item variant="text" style="width: 100%; height: 30px; margin: 10px 0" />
                <el-skeleton-item variant="text" style="width: 100%; height: 30px; margin: 10px 0" />
                <el-skeleton-item variant="text" style="width: 100%; height: 30px; margin: 10px 0" />
                <el-skeleton-item variant="text" style="width: 20%; height: 30px; margin: 10px 0" />
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #default>
        <el-row class="login-page">
          <el-col :span="12" class="bg"></el-col>
          <el-col :span="6" :offset="3" class="form">
            <el-form :model="registerForm" ref="form" :rules="rules" size="large" autocomplete="off" v-if="isRegister">
              <el-form-item>
                <h1>注册</h1>
              </el-form-item>
              <el-form-item prop="username">
                <el-input v-model="registerForm.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="registerForm.password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item prop="repassword">
                <el-input
                  v-model="registerForm.repassword"
                  @keyup.enter="register(registerForm)"
                  :prefix-icon="Lock"
                  type="password"
                  placeholder="请输入再次密码"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="register(registerForm)" :loading="loading" class="button" type="primary" auto-insert-space> 注册 </el-button>
              </el-form-item>
              <el-form-item class="flex">
                <el-link type="info" :underline="false" @click="isRegister = false"> ← 返回 </el-link>
              </el-form-item>
            </el-form>
            <el-form :model="loginForm" ref="form" :rules="rules" size="large" autocomplete="off" v-else>
              <el-form-item>
                <h1>登录</h1>
              </el-form-item>
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  @keydown.enter="login(loginForm)"
                  name="password"
                  :prefix-icon="Lock"
                  type="password"
                  placeholder="请输入密码"
                ></el-input>
              </el-form-item>
              <el-form-item class="flex">
                <div class="flex">
                  <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                  <el-link type="primary" :underline="false">忘记密码？</el-link>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button @click="login(loginForm)" :loading="loading" class="button" type="primary" auto-insert-space>登录</el-button>
              </el-form-item>
              <el-form-item class="flex">
                <el-link type="info" :underline="false" @click="isRegister = true"> 注册 → </el-link>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </template>
    </el-skeleton>
  </el-space>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
